<?php

class Emms_Form_Admin_Client extends HTech_Form
{
    protected $_primary  = 'ClientId';
    
    private $_groupOptions = array();
    private $_officerOptions = array();
    private $_communityOptions = array();
    private $_defaultGroup;
    private $_defaultOfficer;
    private $_defaultCommunity;
    
    public function __construct() 
    {
        parent::__construct(); 
        $this->_setOptions();
        
        $this->setName('Client');
        
        $this->setAttrib('title', $this->translate("Client form"));
        $this->setDescription($this->translate("Edit client info or add a new one"));       
        
        $clientId = new Zend_Form_Element_Hidden('ClientId'); 
        
        $cipherId = new Zend_Form_Element_Hidden('CipherId');
        $cipherId->addValidator('Callback', true, array('callback' => array($this, 'checkCipherIdCallback')))
            ->addValidator('Db_NoRecordExists', true, array(
                'table' => 'clients', 
                'field' => 'CipherId', 
                'exclude' => array('field' => 'ClientId', 'value' => $this->_id)))
            ->addErrorMessage($this->translate("Non valid or duplicated client entry"))
            ->setDecorators(array('ViewHelper','Errors'));
        
        $savingsProductId = new Zend_Form_Element_Select('SavingsProductId');
        $savingsProductId->setLabel("Savings product")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(
                    array('' => '--- ' . $this->translate('Select option')) + $this->_db->fetchPairs('select SavingsProductId, Name from savings_products')); 
        
        $officerUserId = new Zend_Form_Element_Select('OfficerUserId');
        $officerUserId->setLabel("Loan officer")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions($this->_officerOptions);
                
        $groupId = new Zend_Form_Element_Select('GroupId');
        $groupId->setLabel("Group")                
            ->setAttrib('size','1')
            ->addMultiOptions($this->_groupOptions);  

        $communityId = new Zend_Form_Element_Select('CommunityId');
        $communityId->setLabel("Community")               
            ->setRequired(true)               
            ->setAttrib('size','4')
            ->addValidator('GreaterThan', true, array('min' => 0))
            ->addMultiOptions($this->_communityOptions)
            ->addErrorMessage($this->translate("Required field, can't be empty")); 
              
        $countryId = new Zend_Form_Element_Select('CountryId');
        $countryId->setLabel("Country")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(
                    array('' => '--- ' . $this->translate('Select option')) + $this->_db->fetchPairs('select CountryId, Country from countries'));  
                        
        $codeType = new Zend_Form_Element_Select('CodeType');
        $codeType->setLabel("Identity type")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array(
                'Gov. code' => $this->translate("Gov. code"), 
                'Passport' => $this->translate("Passport"), 
                'Foreign Id' => $this->translate("Foreign Id"),
                'Other' => $this->translate("Other")));
                        
        $code = new Zend_Form_Element_Text('Code');
        $code->setLabel("Identity number")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")));
        if($this->_request->getPost('CodeType') == 'Gov. code') {
            $code->addValidator('Regex', true, array(
                'pattern' => $this->_conf->regex->govCode->pattern,
                'messages' => sprintf($this->translate("Valid format: %s"), $this->_conf->regex->govCode->message))); 
        }
        
        $birthdate = new Zend_Form_Element_Text('Birthdate');
        $birthdate->setLabel("Birthdate")
            ->setRequired(true)
            ->addValidator('Date', true, array('format' => 'yyyy-MM-dd'))
            ->addErrorMessage($this->translate("Enter a valid date. Format: YYYY-MM-DD"));
                
        $gender = new Zend_Form_Element_Select('Gender');
        $gender->setLabel("Gender")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array('Male' => $this->translate("Male"), 'Female' => $this->translate("Female")));  
        
        $firstName = new Zend_Form_Element_Text('FirstName');
        $firstName->setLabel("First name")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 2,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));
        
        $middleName = new Zend_Form_Element_Text('MiddleName');
        $middleName->setLabel("Middle name")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 1,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));
        
        $lastName = new Zend_Form_Element_Text('LastName');
        $lastName->setLabel("Last name")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 2,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));

        $secondLastName = new Zend_Form_Element_Text('SecondLastName');
        $secondLastName->setLabel("Second last name")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', false, array(
                    'min' => 1,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));

        $nickName = new Zend_Form_Element_Text('NickName');
        $nickName->setLabel("Nickname")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', false, array(
                    'min' => 1,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));
                        
        $skills = new Zend_Form_Element_Textarea('Skills');
        $skills->setLabel("Skills")
            ->addFilter('Alnum', array('allowwhitespace' => true))
            ->setAttrib('rows', 2)
            ->addValidator('StringLength', false, array(
                    'min' => 1,
                    'max' => 255,
                    'messages' => $this->translate("From %min% to %max% characters only")));  

        $handicap = new Zend_Form_Element_Select('Handicap');
        $handicap->setLabel("Handicap")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array(
                'None' => $this->translate("None"), 
                'Blind' => $this->translate("Blind"), 
                'Deaf-mute' => $this->translate("Deaf-mute"), 
                'Missing a limb' => $this->translate("Missing a limb"),
                'Physically challenged' => $this->translate("Physically challenged"),
                'Other' => $this->translate("Other condition")));

        $education = new Zend_Form_Element_Select('Education');
        $education->setLabel("Education")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array(
                'None' => $this->translate("None"), 
                'Some primary school' => $this->translate("Some primary school"), 
                'Primary school' => $this->translate("Primary school"), 
                'Some high school' => $this->translate("Some high school"), 
                'High school' => $this->translate("High school"),
                'Some college' => $this->translate("Some college"),
                'College' => $this->translate("College"),
                'Some university' => $this->translate("Some university"),
                'University' => $this->translate("University"),
                'Graduate' => $this->translate("Graduate")));

        $maritalStatus = new Zend_Form_Element_Select('MaritalStatus');
        $maritalStatus->setLabel("Marital status")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array(
                'Married' => $this->translate("Married"), 
                'Single' => $this->translate("Single"), 
                'Cohabitate' => $this->translate("Cohabitate"), 
                'Divorced' => $this->translate("Divorced"), 
                'Widow' => $this->translate("Widow")));

        $spouseName = new Zend_Form_Element_Text('SpouseName');
        $spouseName->setLabel("Spouse name")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', false, array(
                    'min' => 1,
                    'max' => 255,
                    'messages' => $this->translate("From %min% to %max% characters only")));
        
        $children = new Zend_Form_Element_Text('Children');
        $children->setLabel("Children")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Digits')
            ->addValidator('Int', true, array(
                    'messages' => $this->translate("Only numeric values allowed")));
        
        $dependents = new Zend_Form_Element_Text('Dependents');
        $dependents->setLabel("Dependents")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Digits')
            ->addValidator('Int', true, array(
                    'messages' => $this->translate("Only numeric values allowed")));
        
        $homePhone = new Zend_Form_Element_Text('HomePhone');
        $homePhone->setLabel("Home phone")
            ->addValidator('Regex', true, array(
                    'pattern' => $this->_conf->regex->tel->pattern,
                    'messages' => sprintf($this->translate("Valid format: %s"),$this->_conf->regex->tel->message)));    
        
        $mobilePhone = new Zend_Form_Element_Text('MobilePhone');
        $mobilePhone->setLabel("Mobile phone")
            ->addValidator('Regex', true, array(
                    'pattern' => $this->_conf->regex->tel->pattern,
                    'messages' => sprintf($this->translate("Valid format: %s"),$this->_conf->regex->tel->message))); 

        $email = new Zend_Form_Element_Text('Email');
        $email->setLabel("Email")      
            ->addValidator('EmailAddress', true)
            ->addFilter('StringToLower')
            ->addFilter('StringTrim')
            ->addErrorMessage($this->translate("Enter a valid email address")); 
        
        $homeAddress = new Zend_Form_Element_Textarea('HomeAddress');
        $homeAddress->setLabel("Home address")
            ->addFilter('Alnum', array('allowwhitespace' => true))
            ->setAttrib('rows', 2);
                        
        $comments = new Zend_Form_Element_Textarea('Comments');
        $comments->setLabel("Comments")
            ->addFilter('Alnum', array('allowwhitespace' => true))
            ->setAttrib('rows', 2); 
        
        $submit = new Zend_Form_Element_Submit('Submit');
        $submit->setLabel("Submit")
            ->addDecorator(new HTech_Form_Decorator_Button(array('type' => 'submit')));
                
        $this->setDecorators(array(array('ViewScript', array('viewScript' => 'client/_form_add.phtml'))));
        
        $this->addElements(array($savingsProductId,$officerUserId, $groupId, $countryId, $codeType, $code, $birthdate, $firstName, $middleName, $lastName, $secondLastName,
            $nickName, $handicap, $skills, $education, $gender, $maritalStatus, $spouseName, $children, $dependents, $email, $mobilePhone, $homePhone, 
            $communityId, $homeAddress, $comments,$submit,$clientId,$cipherId));
        
        $this->setDefaults(array('GroupId' => $this->_defaultGroup, 'OfficerUserId' => $this->_defaultOfficer, 'CommunityId' => $this->_defaultCommunity)); 
    }
    
    public function checkCipherIdCallback($cipherId, $args) 
    {
        if($cipherId != md5($args['CountryId'] . $args['Code'] . $args['CodeType'] . $args['Gender'])) return false;   
        return true;
    }
    
    private function _setOptions()
    {
        if($this->_request->isPost()) {
            $param = $this->_request->getPost(); 
            $this->_defaultOfficer = (int) $param['OfficerUserId']; 
            $this->_defaultGroup = isset($param['GroupId']) ? (int) $param['GroupId'] : 0;
            $this->_defaultCommunity = isset($param['CommunityId']) ? $param['CommunityId'] : 0; 
            if($param['ClientId']) { echo 'ClientId: '. $param['ClientId']. '<br />';
                if(Clients::getActiveLoansCount((int) $param['ClientId'])) { 
                    $this->_officerOptions = Officers::getOfficerOptions('Client', (int) $param['ClientId']);
                    $this->_groupOptions = Groups::getGroupOptions('Client', (int) $param['ClientId']);
                    $this->_communityOptions = Communities::getCommunityOptions('Client', (int) $param['ClientId']);
                    return;
                }
            }
            $this->_officerOptions = Officers::getOfficerOptions('Client', (int) $param['ClientId']); 
            $this->_groupOptions = Groups::getGroupOptions('Officer', (int) $param['OfficerUserId']);
            $this->_communityOptions = (isset($param['GroupId'])&&((int) $param['GroupId'] > 0)) ? 
                Communities::getCommunityOptions('Group', (int) $param['GroupId']) : 
                (isset($param['OfficerUserId']) ? Communities::getCommunityOptions('Officer', (int) $param['OfficerUserId']) : array()); 
            return;
        } else {
            $param = $this->_request->getParams();
            if(isset($param['id'])&&(int) $param['id'] > 0) {
                $this->_setOptionsByClient((int) $param['id']);
            } elseif (isset($param['group'])&&(int) $param['group'] > 0) {
                $this->_setOptionsByGroup((int) $param['group']);
            } elseif (isset($param['officer'])&&(int) $param['officer'] > 0) {
                $this->_setOptionsByOfficer((int) $param['officer']);
            } else {
                $this->_officerOptions = Officers::getOfficerOptions();
            }
        }
    }
    
    private function _setOptionsByClient($id)
    {
        $clients = new Clients();
        try {
            $client = $clients->getRecord($id);
        } catch (Exception $e) {
            $this->deny($e);
        }
        $this->_defaultOfficer = $client->d->OfficerUserId;
        $this->_defaultGroup = $client->d->GroupId;     
        $this->_defaultCommunity = $client->d->CommunityId;
        
        $this->_officerOptions = Officers::getOfficerOptions('Client', $id);
        $this->_groupOptions = Groups::getGroupOptions('Client', $id);
        $this->_communityOptions = Communities::getCommunityOptions('Client', $id);  
        
    }
    
    private function _setOptionsByOfficer($id)
    {
        $officers = new Officers();
        try {
            $officer = $officers->getRecord($id);
        } catch (Exception $e) {
            $this->deny($e);
        }
        $this->_defaultOfficer = $officer->d->OfficerUserId; 
        $this->_defaultGroup = 0;
        $this->_defaultCommunity = 0; 
        
        $this->_officerOptions = Officers::getOfficerOptions();
        $this->_groupOptions = Groups::getGroupOptions('Officer', $officer->d->OfficerUserId);
        $this->_communityOptions = Communities::getCommunityOptions('Officer', $officer->d->OfficerUserId);
    }
    
    private function _setOptionsByGroup($id)
    {
        $groups = new Groups();
        try {
            $group = $groups->getRecord($id);
        } catch (Exception $e) {
            $this->deny($e);
        }
        $this->_defaultOfficer = $group->d->OfficerUserId; 
        $this->_defaultGroup = $group->d->GroupId;
        $this->_defaultCommunity = $group->d->CommunityId; 
        
        $this->_officerOptions = Officers::getOfficerOptions();
        $this->_groupOptions = Groups::getGroupOptions('Officer', $group->d->OfficerUserId);
        $this->_communityOptions = Communities::getCommunityOptions('Group', $group->d->GroupId);
    }
}